package com.aurora.leetcode.answer;

/**
 * @author : Aurora
 * @date : 2024/3/31 13:34
 * @description 二分查找——704
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，
 * 写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 */
public class BinarySearch_704 {
    public int search(int[] nums, int target) {
        if (nums.length == 0) return -1;
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int temp = (right + left) >> 1;
            if (nums[temp] == target) {
                return temp;
            }
            if (target > nums[temp]) {
                left = temp + 1;
            } else {
                right = temp - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearch_704 binarySearch704 = new BinarySearch_704();
//        nums = [-1,0,3,5,9,12], target = 9
//        nums = [-1,0,3,5,9,12], target = 2
        int[] num = new int[]{-1, 0, 3, 5, 9, 12};
        Integer target = 9;
        System.out.println(binarySearch704.search(num, target));
    }
}
